<template>
  <div>
    <el-form
      ref="ruleFormRef"
      :model="SpuParams"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="SpuParams.spuName" />
      </el-form-item>
      <el-form-item label="品牌" prop="name">
        <el-select v-model="SpuParams.tmId">
          <el-option
            v-for="item in AllTradeMark"
            :key="item.id"
            :label="item.tmName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="描述" prop="name">
        <el-input type="textarea" v-model="SpuParams.description" />
      </el-form-item>
      <el-form-item label="图片" prop="name">
        <el-upload
          v-model:file-list="imgList"
          action="/api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :before-upload="beforeUpload"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售" prop="name">
        <el-select
          v-model="saleAttrIdAndValueName"
          :placeholder="
            unSelectSaleAttr.length
              ? `还未选择${unSelectSaleAttr.length}个`
              : '无'
          "
        >
          <el-option
            v-for="item in unSelectSaleAttr"
            :key="item.id"
            :label="item.name"
            :value="`${item.id}:${item.name}`"
          />
        </el-select>

        <el-button
          :disabled="!saleAttrIdAndValueName"
          type="primary"
          icon="Plus"
          @click="addSaleAttr"
          >添加属性值</el-button
        >

        <el-table :data="saleAttr" :border="true">
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="saleAttrName" label="销售名称" width="120" />
          <el-table-column prop="description" label="销售值">
            <template #default="{ row }">
              <el-tag
                closable
                v-for="(item, i) in row.spuSaleAttrValueList"
                :key="item.id"
                @close="row.spuSaleAttrValueList.splice(i, 1)"
              >
                {{ item.saleAttrValueName }}
              </el-tag>

              <el-input
                v-if="row.flag"
                v-model="row.saleAttrValue"
                size="small"
                @blur="toLook(row)"
              />

              <el-button
                v-else
                type="primary"
                size="small"
                icon="Plus"
                @click="toEdit(row)"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row, $index }">
              <el-popconfirm
                :title="`确认删除${row.spuName}`"
                width="200px"
                @confirm="saleAttr.splice($index, 1)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="small"
                    icon="Delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :disabled="!saleAttr.length" @click="save"
          >保存</el-button
        >
        <el-button type="primary" @click="cancelSpu">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import {
  reqAllTrademark,
  reqSpuImageList,
  reqSpuHasSAleAttr,
  reqAllSaleAttr,
  reqAddOrUpdateSpu
} from '@/api/product/spu/index'
import type {
  SaleAttrValue,
  SpuData,
  Trademark,
  SpuImage,
  SaleAttr,
  HasSaleAttr,
  AllTrademark,
  SpuHasImg,
  SaleAttrResponseData,
  HasSaleAttrResponseData
} from '@/api/product/spu/type'

import type { UploadProps } from 'element-plus'

import { ElMessage } from 'element-plus'
const rules = {}

const $emit = defineEmits(['cancelSpu', 'saveSpu'])
const cancelSpu = () => {
  $emit('cancelSpu')
}

const AllTradeMark = ref<Trademark[]>([])
const imgList = ref<SpuImage[]>([])
const saleAttr = ref<SaleAttr[]>([])
const allSaleAttr = ref<HasSaleAttr[]>([])

const SpuParams = ref<SpuData>({
  category3Id: '',
  spuName: '',
  tmId: '',
  description: '',
  spuImageList: [],
  spuSaleAttrList: []
})
const initHasSpuData = async (spu: SpuData) => {
  const result: AllTrademark = await reqAllTrademark()

  if (spu.id) {
    const result1: SpuHasImg = await reqSpuImageList(spu.id as number)
    const result2: SaleAttrResponseData = await reqSpuHasSAleAttr(
      spu.id as number
    )
    imgList.value = result1.data.map((item) => ({
      name: item.imgName,
      url: item.imgUrl
    }))
    saleAttr.value = result2.data
  }
  const result3: HasSaleAttrResponseData = await reqAllSaleAttr()
  AllTradeMark.value = result.data
  allSaleAttr.value = result3.data

  SpuParams.value = spu
}

const dialogVisible = ref<boolean>(false)
const dialogImageUrl = ref<string>('')

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const beforeUpload = (uploadFile: File) => {
  if (uploadFile.type === 'image/png' || uploadFile.type === 'image/jpeg') {
    return true
  } else {
    return false
  }
}

const unSelectSaleAttr = computed(() => {
  const unSelectAttr = allSaleAttr.value.filter((item) => {
    return saleAttr.value.every((item1) => {
      return item.name !== item1.saleAttrName
    })
  })

  return unSelectAttr
})

const saleAttrIdAndValueName = ref<string>('')

const addSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
  const newSaleAttr: SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: []
  }
  saleAttr.value.push(newSaleAttr)

  saleAttrIdAndValueName.value = ''
}

const toEdit = (row: SaleAttr) => {
  row.flag = true
  row.saleAttrValue = ''
}
const toLook = (row: SaleAttr) => {
  const { baseSaleAttrId, saleAttrValue } = row
  const newSaleAttrValue: SaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue!
  }

  if (saleAttrValue!.trim() === '') {
    ElMessage({
      type: 'error',
      message: '属性值不能为空'
    })
    return
  }

  const repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName === saleAttrValue
  })
  if (repeat) {
    ElMessage({
      type: 'error',
      message: '属性值重复了'
    })
    return
  }

  row.spuSaleAttrValueList.push(newSaleAttrValue)

  row.flag = false
}

const save = async () => {
  SpuParams.value.spuImageList = imgList.value.map((item: any) => ({
    imgName: item.name,
    imgUrl: item?.response?.data || item.url
  }))

  SpuParams.value.spuSaleAttrList = saleAttr.value

  await reqAddOrUpdateSpu(SpuParams.value)

  ElMessage({
    type: 'success',
    message: SpuParams.value.id ? '更新成功' : '添加成功'
  })

  saveSpu(SpuParams.value.id?'update':'add')
}
const saveSpu = (type:string) => {
  $emit('saveSpu',type)
}

const initAddSpu = async (c3Id: number | string) => {
  Object.assign(SpuParams.value, {
    category3Id: '',
    spuName: '',
    tmId: '',
    description: '',
    spuImageList: [],
    spuSaleAttrList: []
  })
 delete SpuParams.value.id
  imgList.value= []
  saleAttr.value= []
  saleAttrIdAndValueName.value=''

  const result: AllTrademark = await reqAllTrademark()
  const result3: HasSaleAttrResponseData = await reqAllSaleAttr()
  AllTradeMark.value = result.data
  allSaleAttr.value = result3.data

  SpuParams.value.category3Id = c3Id
}
defineExpose({ initHasSpuData, initAddSpu })
</script>

<style scoped></style>
